package com.simou.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simou.dao.DishMapper;
import com.simou.dto.DishDto;
import com.simou.entity.Dish;
import com.simou.entity.DishFlavor;
import com.simou.service.DishFlavorService;
import com.simou.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Transactional
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    DishService dishService;

    @Override
    public void saveWithFlavor(DishDto dishDto) {
        // 1.保存菜品信息到dish表中
        // 保存之后dishDto获得Id
        this.save(dishDto);

        // 取出dishId
        Long id = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();
        // dto的flavors（可能有多个）的dishId赋值为id
        // 写法一
//        flavors.stream().map((item)->{
//            item.setDishId(id);
//            return item;
//        }).collect(Collectors.toList());

        // 写法二
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }

        // 2.保存菜品口味到dishFlavor数据表中
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        DishDto dishDto = new DishDto();

        // 1.先查dish
        Dish dish = dishService.getById(id);

        // 2.再根据dish的id查dishFlavor
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);

        // 3.将所有属性放入dishDto中
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(flavors);

        return dishDto;
    }

    @Override
    public void updateByIdWithFlavor(DishDto dishDto) {
        // 1.根据id删除dishFlavor的记录(解除关联)
        Long id = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        dishFlavorService.remove(queryWrapper);

        // 2.修改dish表
//        Dish dish = new Dish();
//        BeanUtils.copyProperties(dishDto,dish);
//        dishService.updateById(dish);
        dishService.updateById(dishDto);    // 与👆相等

        // 3.重新添加dishFlavor记录
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            // 给flavors所有元素附上id
            flavor.setDishId(id);
        }

        dishFlavorService.saveBatch(flavors);

    }
}
